package com.tarena.lbs.coupon.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarena.lbs.coupon.dao.mapper.UserCouponsMapper;
import com.tarena.lbs.coupon.dao.repository.UserCouponsRepository;
import com.tarena.lbs.coupon.pojo.po.UserCouponsPO;
import com.tarena.lbs.coupon.pojo.query.UserCouponCodeQuery;
import com.tarena.lbs.coupon.pojo.query.UserCouponQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


@Slf4j
@Repository
public class UserCouponsRepositoryImpl implements UserCouponsRepository {

    @Autowired
    private UserCouponsMapper userCouponsMapper;

    @Override
    public Page<UserCouponsPO> receiveList(UserCouponQuery couponQuery) {
        Page<UserCouponsPO> page = new Page<>(couponQuery.getPageNo(), couponQuery.getPageSize());
        QueryWrapper<UserCouponsPO> queryWrapper = generateQuery(couponQuery);
        return userCouponsMapper.selectPage(page, queryWrapper);
    }

    @Override
    public UserCouponsPO receiveDetail(Integer UserId, String couponCode) {
        QueryWrapper<UserCouponsPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", UserId);
        queryWrapper.eq("coupon_code", couponCode);
        return userCouponsMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateUserCoupons(UserCouponsPO userCouponsPO) {
        userCouponsMapper.updateById(userCouponsPO);
    }

    @Override
    public void insert(UserCouponsPO userCouponsPO) {
        userCouponsMapper.insert(userCouponsPO);
    }

    private QueryWrapper<UserCouponsPO> generateQuery(UserCouponQuery couponQuery) {
        QueryWrapper<UserCouponsPO> queryWrapper = new QueryWrapper<>();
        if (couponQuery.getUserId() != null) {
            queryWrapper.eq("user_id", couponQuery.getUserId());
        }
        if (couponQuery.getCouponType() != null) {
            queryWrapper.eq("coupon_type", couponQuery.getCouponType());
        }
        if (couponQuery.getStatus() != null) {
            queryWrapper.eq("status", couponQuery.getStatus());
        }
        if (couponQuery.getOrderNo() != null) {
            queryWrapper.eq("order_no", couponQuery.getOrderNo());
        }
        if (couponQuery.getReceiveChannel() != null) {
            queryWrapper.eq("receive_channel", couponQuery.getReceiveChannel());
        }
        return queryWrapper;
    }
}
